import { Component, ViewChild, AfterViewChecked } from '@angular/core';
import { Router, NavigationExtras } from '@angular/router';
import { NgForm } from '@angular/forms';
import { tap, filter, switchMapTo } from 'rxjs/operators';

import { AuthService } from '../../service/AuthService';
import { UserService } from '../../service/UserService';
import { User } from '../../models/User';

@Component({
    selector: 'app-register',
    templateUrl: 'register.html',
    styleUrls: ['register.css'],
})
export class RegisterComponent implements AfterViewChecked {

    user: User;
    loading: Boolean = false;
    messages = {
        username: '',
        password: '',
        confirmPassword: ''
    };

    @ViewChild('registerForm')
    registerForm: NgForm;

    ngAfterViewChecked() {
        // Angular的“单向数据流”规则禁止在一个视图已经被组合好之后再更新视图.而此时已组合好
        if (this.registerForm) {
            this.registerForm.valueChanges.subscribe(data => this.checkValidate());
        }
    }

    constructor(
        private authService: AuthService,
        private userService: UserService,
        private router: Router
    ) {
        this.user = new User();

    }

    register() {
          this.checkValidate(true);
          if (this.registerForm.invalid) {
              return false;
          }
          this.userService.isExist(this.user.username).pipe(
            tap((res) => {
              if (!res.success) {
                  this.messages.username = RegisterComponent.ErrorMessages.username.hasExist;
              }
          }),
          // 如果success为false过滤掉。不执行
          filter(res => res.success),
          switchMapTo(this.userService.register(this.user)))
              .subscribe((res: {success: boolean, res: User}) => {
                // 赋值给一个属性，
                this.authService.user = res.res;
                // 改变所有user，其他页面刷新
                this.authService.userSource.next(res.res);
                const redirect: any[] = this.authService.redirectUrl ?
                  ['', {outlets: {primary: this.authService.redirectUrl, auth: 'login'}}]
                      : ['', {outlets: {auth: 'login'}} ];
                const navigationExtras: NavigationExtras = {
                      queryParamsHandling: 'merge',
                      preserveFragment: true
                  };
                  this.router.navigate(redirect, navigationExtras);

              });


    }


    checkValidate(isSubmit?: boolean) {
        const form = this.registerForm;

        for (const field in RegisterComponent.ErrorMessages) {

            const control = form.controls[field];

            if (control && control.valid) {
                this.messages[field] = '';
            }
            if (control && (control.dirty || isSubmit) && !control.valid) {
                const messages = RegisterComponent.ErrorMessages[field];
                if (control.errors) {
                    this.messages[field] = messages[Object.keys(control.errors)[0]];
                }
            }

        }
    }

    static ErrorMessages = {
        username: {
            required: '用户名不能为空',
            hasExist: '用户名已存在',
            pattern: '以字母开头，由4-20个字母、数字和"_"组成'
        },
        password: {
            required: '密码不能为空',
            pattern: '大于6位，必须由数字，字母共同组成'
        },
        confirmPassword: {
            required: '确认密码不能为空',
            pattern: '两次密码不一样'
        }
    };

}
